#!/usr/bin/env python

import re
import urllib2

# Still not a lot of test


class Google:
    """Allows the user to make searches in the Google webpage.

    To search using the advance options of Google use the options like
    site:youtube.com
    """

    def __init__(self):
        self.opener = urllib2.build_opener()
        self.pattern = re.compile(
            r"""Resultados da procura.*?<a href="(.*?)\" """, re.DOTALL)

    def search(self, string):
        """Searches a string in the google webpage.

        Returns a string with the first webpage if it finds anything.
        Returns 1 if it doesn't find anything.
        """
        string = string.replace(" ", "+")

        url = "http://google.pt/search?q=" + string
        request = urllib2.Request(url)
        request.add_header("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; " \
            "pt-PT; rv:1.9) Gecko/2008052912 Firefox/3.0")
        feeddata = self.opener.open(request).read()
        try:
            site = re.search(self.pattern, feeddata).groups()[0]
            return site
        except AttributeError: # re.search didn't found nothing
            print "Site not found"
            return 1

#class Google:
    #def __init__(self):
        #self._createSocket()
        #self.pattern = re.compile(r"""<a href="(.*?)" """)
        #self.tries = 5
    #def _createSocket(self):
        #self.soc_google = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #self.soc_google.connect(("www.google.com", 80))
    #def _search(self, string):
        #string = string.replace(" ", "+")
        #self.soc_google.send(r"""GET /search?hl=pt-PT&q=%s http/1.1
#Host: www.google.pt

#""" % string)
        #time.sleep(2)
        #content = self.soc_google.recv(32768)
        #try:
            #tmp = content.split("\n")[15]
        #except IndexError:
            #return "IndexError"
        ##tmp = re.findall(self.pattern, tmp)
        #site = re.search(self.pattern, tmp).groups()[0]
        #self.soc_google.close()
        #self._createSocket()
        #return site

    #def search(self, string):
        #while self.tries >= 0:
            #site = self._search(string)
            #if site.startswith("/"):
                #self.tries -= 1
            #elif site.startswith("http://images.google.pt/"):
                #self.tries -= 1
            #elif site == "IndexError":
                #self.tries -= 1
            #else:
                #self.tries = -1

        #self.tries = 5
        #return site

    #def __del__(self):
        #self.soc_google.close()

if __name__ == "__main__":
    g = Google()
    site = g.search("portugal a programar")
    print site
